﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ext.Net.Utilities;
using Ext.Net;
using MemberMgr.Data.BusinessObjects;
using MemberMgr.Data.ManagerObjects;
using MemberMgr.Website.Common;
using System.Data;

namespace MemberMgr.Website.Product
{
    public partial class AddCost :Common.PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [DirectMethod]
        protected void btnSearchProduct_Click(object sender, EventArgs e)
        {
        }

        [DirectMethod]
        protected void btnSearchMember_Click(object sender, DirectEventArgs e)
        {
            if (e.ExtraParams["Tag"] != "Search")
            {
                this.lblMemberInfo.Html = string.Empty;
                this.hdnMemberID.Value = string.Empty;
            }
            else
            {
                SearchMember();
            }
        }

        [DirectMethod]
        protected void btnSave_Click(object sender, EventArgs e)
        {
        
        
        }

        [DirectMethod(Namespace = "X")]
        public void SearchKeyPress()
        {
            SearchMember();
        }

        private void SearchMember()
        {
            string strMemberCode = string.Empty;

            strMemberCode = this.txtSearchNo.Text;

            //Search Member
            ItMemberManager memMgr = Common.CommonUtil.managerFactory.GettMemberManager();

            IList<tMember> memberlist = memMgr.GetMemberByCardNO(strMemberCode);

            if (memberlist != null && memberlist.Count > 0)
            {
                tMember member = memberlist.FirstOrDefault();

                //设置会员信息
                this.lblMemberInfo.Text = string.Empty;

                this.lblMemberInfo.Html += "<B>会员姓名:</B>" + member.Membername + "&nbsp;&nbsp;";
                this.lblMemberInfo.Html += "<B>会员类型:</B>" + member.Membertype + "&nbsp;&nbsp;";
                this.lblMemberInfo.Html += "<B>会员联系方式:</B>" + member.Membertel + "&nbsp;&nbsp;";
                this.lblMemberInfo.Html += "<B>会员地址:</B>" + member.Memberaddress + "&nbsp;&nbsp;";

                this.hdnMemberID.Value = member.Id;

            }
            else
            {
                this.lblMemberInfo.Html = string.Format("&nbsp;&nbsp;&nbsp;&nbsp;<font color='red'>{0}</font>", "没有输入的会员卡号，请确认后重试。");
                this.hdnMemberID.Value = string.Empty;
                this.txtSearchNo.Focus();
            }

        }

        [DirectMethod]
        protected void btnSearchWin_Click(object sender, DirectEventArgs e)
        {
            BindDataSource();
        }

        private void BindDataSource()
        {
            string productName = this.txtSearchProductName.Text.Trim();

            ItProductManager productMgr = Common.CommonUtil.managerFactory.GettProductManager();
            IList<tProduct> list = null;

            if (!string.IsNullOrEmpty(productName))
            {
                list = productMgr.GetProductsByName(productName);
            }
            else
            {
                list = productMgr.GetAll();
            }

            if (list != null)
            {
                DataTable dt = this.GetMemberInfoDataTable();

                foreach (tProduct item in list)
                {
                    decimal productSUM = 0;

                    productSUM += item.TProductInlogs.Sum<tProductInlog>(p => p.Insum);
                    productSUM = productSUM - item.TProductOutlogs.Sum<tProductOutlog>(p => p.Outsum);

                    dt.Rows.Add(
                        item.Id,
                        item.Productname,
                        item.Producttype,
                        item.Maker,
                        item.Price,
                        item.Comment,
                        productSUM
                        );
                }

                this.storeProduct.DataSource = dt;
                this.storeProduct.DataBind();
            }
        }

        private DataTable GetMemberInfoDataTable()
        {
            DataTable dt = new DataTable();

            dt.Columns.AddRange(new DataColumn[] { 
                new DataColumn() { ColumnName="ID",DataType=typeof(uint)},
                new DataColumn() { ColumnName="PRODUCTNAME",DataType=typeof(string)},
                new DataColumn() { ColumnName="PRODUCTTYPE",DataType=typeof(string)},
                new DataColumn() { ColumnName="MAKER",DataType=typeof(string)},
                new DataColumn() { ColumnName="PRICE",DataType=typeof(double)},
                new DataColumn() { ColumnName="COMMENT",DataType=typeof(string)},
                new DataColumn() { ColumnName="PRODUCTSUM",DataType=typeof(decimal)}
            });

            return dt;
        }


        [DirectMethod]
        protected void SelectedProduct(object sender, DirectEventArgs e)
        {
            if (string.IsNullOrEmpty(e.ExtraParams["productid"]))
            {
                return;
            }

            uint productid = uint.Parse(e.ExtraParams["productid"]);

            ItProductManager productMgr = Common.CommonUtil.managerFactory.GettProductManager();

            tProduct product = productMgr.GetById(productid);

            if (product != null)
            {
                this.lblProductInfo.Html = "";
                this.lblProductInfo.Html += "<B>商品名称:</B>" + product.Productname + "&nbsp;&nbsp;";
                this.lblProductInfo.Html += "<B>制造商:</B>" + product.Maker + "&nbsp;&nbsp;";
                this.lblProductInfo.Html += "<B>价格:</B>" + product.Price + "&nbsp;&nbsp;";
                this.lblProductInfo.Html += "<B>商品类型:</B>" + product.Producttype + "&nbsp;&nbsp;";

                this.hdnProductID.Value = product.Id;
                this.txtProductNo.Text = product.Id.ToString();
                this.hdnPrice.Value = product.Price; 
                this.winProductSearch.Hide();
            }
            else
            {
                this.hdnProductID.Value = string.Empty;
                this.txtProductNo.Text = string.Empty;
                this.lblProductInfo.Html = string.Format("<font color='red'></font>", "当前选择的商品信息不正确，请重新选择.");
                this.hdnPrice.Value = 0;
                this.winProductSearch.Hide();
            }
        }

        [DirectMethod]
        protected void btnCost_Click(object sender, DirectEventArgs e)
        {

            if (string.IsNullOrEmpty(this.hdnMemberID.Text))
            {
                X.Msg.Show(new MessageBoxConfig() { 
                    Buttons=MessageBox.Button.OK,
                    Icon=MessageBox.Icon.ERROR,
                    Message="会员信息不正确，请确认后重试!",
                    Title="错误"
                });

                this.txtSearchNo.Focus();
                return;
            }

            if (string.IsNullOrEmpty(this.hdnProductID.Text))
            {
                X.Msg.Show(new MessageBoxConfig()
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.ERROR,
                    Message = "商品信息不正确，请确认后重试!",
                    Title = "错误"
                });

                this.txtProductNo.Focus();
                return;
            }

            uint memberid = uint.Parse(this.hdnMemberID.Text);
            uint productid = uint.Parse(this.hdnProductID.Text);

            

            ItMemberManager memMgr = Common.CommonUtil.managerFactory.GettMemberManager();
            ItProductManager productMgr = Common.CommonUtil.managerFactory.GettProductManager();

            tProduct product = productMgr.GetById(productid);
            if (product == null)
            {
                X.Msg.Show(new MessageBoxConfig()
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.ERROR,
                    Message = "商品信息不正确，请确认后重试!",
                    Title = "错误"
                });

                this.txtProductNo.Focus();
                return;
            }

            tMember member = memMgr.GetById(memberid);
            if (member == null)
            {
                 X.Msg.Show(new MessageBoxConfig() { 
                    Buttons=MessageBox.Button.OK,
                    Icon=MessageBox.Icon.ERROR,
                    Message="会员信息不正确，请确认后重试!",
                    Title="错误"
                });

                this.txtSearchNo.Focus();
                return;
            }

            ItConsumptionMasterManager cmMgr = Common.CommonUtil.managerFactory.GettConsumptionMasterManager();
            ItConsumptionDetailManager cdMgr = Common.CommonUtil.managerFactory.GettConsumptionDetailManager();

            cmMgr.Session.BeginTransaction();

            try
            {
                ItShopManager shopMgr = Common.CommonUtil.managerFactory.GettShopManager();
                ItUserManager userMgr = Common.CommonUtil.managerFactory.GettUserManager();

                tUser user = userMgr.GetById(base.UserInfo.Id);

                tConsumptionDetail td = new tConsumptionDetail();
                tConsumptionMaster tm = new tConsumptionMaster();

                td.Count = Convert.ToDecimal(this.txtCostNum.Text);
                td.Price = product.Price;
                td.TProduct = product;
                td.TConsumptionMaster = tm;

                tm.Costaddress = user.TShop.Address;
                tm.Costcut = this.txtCostCut.Text.Trim();
                tm.Costtime = DateTime.Now;
                tm.Sum = Convert.ToDecimal(this.txtSum.Text);//product.Price * Convert.ToDecimal(this.txtCostNum.Text) * Convert.ToDecimal(this.txtCostCut.Number);
                tm.TMember = member;
                tm.TShop = user.TShop;
                tm.TConsumptionDetails.Add(td);

                cmMgr.Save(tm);

                cmMgr.Session.CommitChanges();

                this.fpSearchPanel.Reset();
                this.fpSearchProduct.Reset();

                X.Msg.Show(new MessageBoxConfig()
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO,
                    Message = "消费数据添加成功",
                    Title = "信息"
                });

                this.txtSearchNo.Focus();
            }
            catch (Exception ex)
            {
                X.Msg.Show(new MessageBoxConfig()
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.ERROR,
                    Message = "数据保存错误，请重试或联系管理员。",
                    Title = "错误"
                });


                cmMgr.Session.RollbackTransaction();
                Common.CommonUtil.logger.Error(ex.Message, ex);
            }
            
        }
    }
}
